# -*- coding: utf8 -*-
import os
import requests

from cpbox.tool import functocli
from cpbox.tool import utils

from cpapp.configman import ConfigMan

from cpapp.buildinfo import BuildInfoProvider
from cpapp.build import Builder
from cpapp.version import VersionInfo
from cpapp import buildinfo

from cpbox.app.devops import DevOpsApp
from cpapp.oss import AliyunOss

APP_NAME = 'lanling-android'
URL_DEV = 'https://www-sandbox-317.cp-test.yizhoucp.cn/api/tools'
URL_PRE = 'https://www.cp-pre.yizhoucp.cn/api/tools'
URL_PROD = 'https://config.yizhoucp.cn/api/tools'
IMAGE_NAME = 'docker.yizhoucp.cn/android-ci/ci:1.0.0'
CONTAINER_NAME = 'cp-android-app'
APK_BUILD_CMD_DEBUG = 'apkDebug'
APK_BUILD_CMD_RELEASE = 'apkRelease'
DEVELOPER_NAME = "engineer"
DEFAULT_CHANNEL = "default"
RELEASE_NOTE = "【新增】发布动态时可以保存草稿了！\n【优化】优化了语音录制功能，点击、长按任你选！\n【优化】优化了动态发布界面哟～\n【修复】定位不会更新的问题已经修复～"

APP_KEY_FLAVOR_MAP = {
    'lanling': 'lanling',
}
FLAVOR_LIST = ['lanling']

class App(DevOpsApp):

    def __init__(self, *args, **kwargs):
        DevOpsApp.__init__(self, APP_NAME, log_level='debug', **kwargs)
        if 'env' in kwargs:
            self.env = kwargs['env']

        self.app_key = kwargs.get('app_key', 'lanling')
        self.flavor = APP_KEY_FLAVOR_MAP.get(self.app_key, None)

        self.version_name = kwargs.get('version_name', None)
        self.version_code = kwargs.get('version_code', 0)

        self.prj_root_dir = os.path.dirname(self.root_dir)
        self.configman = ConfigMan(self, self.prj_root_dir, self.flavor)
        oss_config = self.read_app_config('app-config')['oss_config']
        self.oss = AliyunOss(self, oss_config)

    def build_sandbox_config(self, quiet=False, dry_fun=False):
        self.env = 'sandbox'
        self.build_config_for(quiet, dry_fun)

    def build_pre_config(self, quiet=False, dry_fun=False):
        self.env = 'pre'
        self.build_config_for(quiet, dry_fun)

    def build_prod_config(self, quiet=False, dry_fun=False):
        self.env = 'prod'
        self.build_config_for(quiet, dry_fun)

    def _init_build_info_provider(self, env=None):
        env = env if env else self.env
        build_info_provider = BuildInfoProvider(self, env, self.app_key, self.flavor)
        build_info_provider.set_version_info(self.version_name, self.version_code)
        return build_info_provider

    def build_test(self, channels='xiaomi', dry_run=True):
        channels = 'default,huawei,meizu,oppo,vivo,google,xiaomi,91,anzhuo,samsung,sogo,lianxiang,jinli,yingyongbao,yingyongbao-1,wandoujia,360,baidu,smartisan,zhihu,6002,6007,6008,6023'
        channels = 'default'
        build_type = buildinfo.BUILD_TYPE_RELEASE
        build_type = buildinfo.BUILD_TYPE_DEBUG
        self.build_apks(build_type, channels, False, dry_run)

    def build_apks(self, build_type, channels, dry_run=True):
        self.logger.info('flavor: %s, build_type: %s, channels: %s, dry_run: %s', self.flavor, build_type, channels, dry_run)
        channels = map(str.strip, channels.split(','))
        build_info_provider = self._init_build_info_provider()
        build_request = buildinfo.BuildRequest(build_info_provider, build_type, channels)

        builder = Builder(self, self.prj_root_dir, dry_run=dry_run)
        builder.process(build_request)
        print(utils.pjson(build_info_provider.to_dict()))

    def release_build(self, version_code, scope, release_note=RELEASE_NOTE):
        build_info_provider = self._init_build_info_provider()
        build_info_provider.release_build(version_code, scope, release_note, DEVELOPER_NAME)

    def _draft_new_version(self, version_name, version_code):
        if version_name is None or version_name == 'None':
            version_name = self.configman.read_version_name()

        author = DEVELOPER_NAME
        build_info_provider = self._init_build_info_provider()
        build_info_provider.draft_new_version(version_name, version_code, author)
        return build_info_provider.get_current_version_info()

    def _update_version_info(self, version_info_raw):
        self.version_name = version_info_raw['version_name']
        self.version_code = version_info_raw['version_code']

    def _update_version_info(self, version_info):
        self.version_name = version_info.version_name
        self.version_code = version_info.version_code

    def build_config_for(self, quiet=False, dry_run=False):
        build_info_provider = self._init_build_info_provider()
        self.configman.update_project_config(build_info_provider, quiet, dry_run)

    def enable_push_type(self, push_type='xiaomi'):
        self.configman.enable_push_type(push_type, False)

    def sdist(self):
        cmd = 'rm -rf dist'
        self.shell_run(cmd)
        cmd = 'python %s/setup.py sdist' % (self.root_dir)
        self.shell_run(cmd)

    def develop(self):
        cmd = 'python %s/setup.py develop --user' % (self.root_dir)
        self.shell_run(cmd)

    def run_tests(self):
        cmd = 'python -m unittest discover'
        self.shell_run(cmd)

    def upload(self):
        self.sdist()
        cmd = 'twine upload --config-file %s/pypirc %s/dist/*' % (self.app_config_dir, self.root_dir)
        self.shell_run(cmd, exit_on_error=False)

    def build_for_cli(self, build_type, channels, dry_run=True, is_upload_pgyer=False, increase_version=False):
        if self.flavor not in FLAVOR_LIST:
            self.app.logger.error('this flavor is illegal: %s' % self.flavor)
            return

        if (increase_version) :
            self.configman.draft_new_version_locally()

        version_info = self.configman._get_version_info(self.env)
        self._update_version_info(version_info)

        self.build_config_for(False, False)
        self.build_apks(build_type, channels, dry_run)

        self.review_version_info(version_info.version_code)

    def update_bulgy_symbol(self):
        if self.env != 'prod':
            print ("update_bulgy_symbol task: ending, wrong evn: %s" % self.env)
            return
        print ("update_bulgy_symbol task: starting..., current env: %s" % self.env)

        app_id = self.read_app_config('app-config')['jni_config']['bugly_app_id']['prod']
        app_key = self.read_app_config('app-config')['jni_config']['bugly_app_key']['prod']

        build_info_provider = self._init_build_info_provider()
        current_version_info = build_info_provider.get_current_version_info()
        version_full_name=current_version_info['version_name'] + '.' + current_version_info['version_code']

        file_path = './app/build/outputs/mapping/yizhou/release/mapping.txt'

        print ("update_bulgy_symbol task: version-full-name:%s" % version_full_name)
        print ("update_bulgy_symbol task: uploading mapping file from path:%s" % file_path)

        payload = {
            "api_version":'1',
            "app_id":app_id,
            "app_key":app_key,
            "symbolType":'1',
            "bundleId":'com.xiaoyu.lanling',
            "productVersion":version_full_name,
            "channel":'%e5%85%a8%e6%b8%a0%e9%81%93',
            "fileName":'mapping.txt'
        }
        files = {'file': open(file_path, 'rb')}
        r = requests.post("https://api.bugly.qq.com/openapi/file/upload/symbol?app_key=%s&app_id=%s" % (app_key,app_id),data=payload,files=files)
        print ("update_bulgy_symbol task: finish, %s" % r.json())

    def review_version_info(self, version_code):
        build_info_provider = self._init_build_info_provider()
        print(utils.pjson(build_info_provider.get_build_info(version_code)))

    def get_apk_path(self, channel, version_code):
        build_info_provider = self._init_build_info_provider()
        apk_path = build_info_provider.get_apk_path(channel, version_code)
        return apk_path

if __name__ == '__main__':
    common_args_option = {
        'args': ['env', 'app_key', 'version_name', 'version_code'],
        'default_values': {
            'env': 'sandbox',
            'app_key': 'lanling',
            'version_name': None,
            'version_code': 0,
        }
    }
    functocli.run_app(App, common_args_option=common_args_option)
